package cn.wolfcode.service.impl;

import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.domain.AccountLog;
import cn.wolfcode.domain.AccountTransaction;
import cn.wolfcode.domain.OperateIntergralVo;
import cn.wolfcode.mapper.AccountLogMapper;
import cn.wolfcode.mapper.AccountTransactionMapper;
import cn.wolfcode.mapper.UsableIntegralMapper;
import cn.wolfcode.service.IUsableIntegralService;
import cn.wolfcode.web.msg.IntergralCodeMsg;
import com.alibaba.fastjson.JSON;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.xml.crypto.Data;
import java.util.Date;


@Service
@Slf4j
public class UsableIntegralServiceImpl implements IUsableIntegralService {
    @Autowired
    private UsableIntegralMapper usableIntegralMapper;
    @Autowired
    private AccountTransactionMapper accountTransactionMapper;
    @Autowired
    private AccountLogMapper accountLogMapper;

    @Override
    @Transactional
    public void decrIntergral(OperateIntergralVo operateIntergralVo) {
        //插入流水记录
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(operateIntergralVo.getPk());//订单编号
        accountLog.setAmount(operateIntergralVo.getValue());//积分变化金额
        accountLog.setGmtTime(new Date());//日志插入时间
        accountLog.setInfo(operateIntergralVo.getInfo());//备注信息
        accountLog.setType(AccountLog.TYPE_DECR);//积分变更类型
        accountLogMapper.insert(accountLog);
        //减少积分
        int count = usableIntegralMapper.decrIntergral(operateIntergralVo.getUserId(),operateIntergralVo.getValue());
        if (count==0){
            throw new BusinessException(IntergralCodeMsg.INTERGRAL_NOT_ENOUGH);
        }
    }

    @Override
    @Transactional
    public void incrIntergral(OperateIntergralVo operateIntergralVo) {
        //插入流水记录
        AccountLog accountLog = new AccountLog();
        accountLog.setPkValue(operateIntergralVo.getPk());//订单编号
        accountLog.setAmount(operateIntergralVo.getValue());//积分变化金额
        accountLog.setGmtTime(new Date());//日志插入时间
        accountLog.setInfo(operateIntergralVo.getInfo());//备注信息
        accountLog.setType(AccountLog.TYPE_INCR);//积分变更类型
        accountLogMapper.insert(accountLog);
        //加积分
        usableIntegralMapper.addIntergral(operateIntergralVo.getUserId(),operateIntergralVo.getValue());
    }

    @Override
    public void incrIntergralTry(OperateIntergralVo operateIntergralVo, BusinessActionContext context) {
        log.info("进入到try");
        //插入事务控制表记录
        commonInsertAccountTranscation(operateIntergralVo,context,AccountTransaction.STATE_TRY,AccountTransaction.INCR_TYPE);
    }

    public void commonInsertAccountTranscation(OperateIntergralVo operateIntergralVo, BusinessActionContext context,int state,String type){
        AccountTransaction accountTransaction = new AccountTransaction();
        accountTransaction.setActionId(context.getBranchId() + "");//分支事务ID
        accountTransaction.setAmount(operateIntergralVo.getValue());//积分变更数值
        accountTransaction.setGmtCreated(new Date());//创建时间
        accountTransaction.setGmtModified(new Date());//修改时间
        accountTransaction.setState(state);//事务状态
        accountTransaction.setTxId(context.getXid());//全局事务ID
        accountTransaction.setType(type);//积分变更类型 1增加积分
        accountTransaction.setUserId(operateIntergralVo.getUserId());//用户ID
        accountTransactionMapper.insert(accountTransaction);
    }

    @Override
    public void incrIntergralCommit(BusinessActionContext context) {
        log.info("进入到confirm");
        //查询事务控制表记录
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId() + "");
        //判断是否为空
        if (accountTransaction==null){
            log.info("异常情况");
        }else if (AccountTransaction.STATE_TRY.equals(accountTransaction.getState())){  //判断是否为初始化
            Object objJson = context.getActionContext("operateIntergralVo");
            OperateIntergralVo operateIntergralVo = JSON.parseObject(objJson + "", OperateIntergralVo.class);
            //继续执行Confirm
            usableIntegralMapper.addIntergral(operateIntergralVo.getUserId(),operateIntergralVo.getValue());
            //修改状态为已提交
            accountTransactionMapper.updateAccountTransactionState(context.getXid(),context.getBranchId() + "",AccountTransaction.STATE_COMMIT,AccountTransaction.STATE_TRY);
        }else if (AccountTransaction.STATE_COMMIT.equals(accountTransaction.getState())){
            //什么都不做处理幂等性
        }else {
            log.info("异常情况");
        }
    }

    @Override
    public void incrIntergralRollback(BusinessActionContext context) {
        log.info("进入到cancel");
        //查询事务控制表记录
        AccountTransaction accountTransaction = accountTransactionMapper.get(context.getXid(), context.getBranchId() + "");
        //判断是否为空
        if(accountTransaction==null){
            //获取VO对象
            Object objJson = context.getActionContext("operateIntergralVo");
            OperateIntergralVo operateIntergralVo = JSON.parseObject(objJson + "", OperateIntergralVo.class);
            //插入事务控制表记录
            commonInsertAccountTranscation(operateIntergralVo,context,AccountTransaction.STATE_CANCEL,AccountTransaction.INCR_TYPE);
        }
        if (AccountTransaction.STATE_TRY.equals(accountTransaction.getState())){    //是否为初始状态
            //继续执行cancel
            //把状态该修改成已回滚
            accountTransactionMapper.updateAccountTransactionState(context.getXid(),context.getBranchId() + "",AccountTransaction.STATE_CANCEL,AccountTransaction.STATE_TRY);
        }else if (AccountTransaction.STATE_COMMIT.equals(accountTransaction.getState())){
            //什么也不做处理幂等性
        }else {
            log.info("异常情况");
        }
    }
}
